<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请人" prop="applicant">
        <user-select v-model="queryParams.applicant" placeholder="请选择申请人" :max-show="1"/>
      </el-form-item>
      <el-form-item label="申请单位" prop="applicantUnit">
        <treeselect v-model="queryParams.applicantUnit" :options="deptOptions" :show-count="true"
                    placeholder="请选择来档单位" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="被导出人" prop="exportedPerson">
        <person-select v-model="queryParams.exportedPerson" multiple placeholder="请选择被导出人"
                       :max-show="1"></person-select>
      </el-form-item>
      <el-form-item label="档案类型" prop="fileType">
        <el-input
            v-model="queryParams.fileType"
            placeholder="请输入档案类型"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applicantDate">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.applicantDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form v-if="false" label-width="68px">
      <el-form-item label="流程Key" prop="processKey">
        <el-input
            v-model="processKey"
            placeholder="请输入流程Key"
            clearable
            size="small"
            style="width:200px"
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['business:exportNet:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['business:exportNet:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['business:exportNet:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['business:exportNet:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="exportNetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="申请人" align="center" prop="applicantName"/>
      <el-table-column label="申请单位" align="center" prop="applicantUnitName"/>
      <el-table-column label="被导出人" align="center" prop="exportedPersonName"/>
      <el-table-column label="申请时间" align="center" prop="applicantDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicantDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="状态" align="center" prop="status" />-->
      <el-table-column label="流程状态" align="center" prop="actBusinessStatus.status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.act_status" :value="scope.row.actBusinessStatus.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.actBusinessStatus.status==='draft'||scope.row.actBusinessStatus.status==='back'||scope.row.actBusinessStatus.status==='cancel'"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:exportNet:edit']"
          >修改
          </el-button>
          <el-button
              v-if="scope.row.actBusinessStatus.status==='draft'||scope.row.actBusinessStatus.status==='back'||scope.row.actBusinessStatus.status==='cancel'"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:exportNet:remove']"
          >删除
          </el-button>
          <el-button
              v-if="scope.row.actBusinessStatus.status==='waiting'"
              size="mini"
              type="text"
              icon="el-icon-back"
              @click="cancelProcessApply(scope.row)"
          >撤销
          </el-button>
          <el-button
              v-if="scope.row.actBusinessStatus.status!=='draft'"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
          >查看
          </el-button>
          <el-button
              v-if="scope.row.actBusinessStatus.status=='finish'"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDown(scope.row)"
          >下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改外网导出对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" @close="cancel" width="800px" append-to-body>
      <el-tabs type="border-card">
        <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="申请人" prop="applicant">
                  <user-select v-model="form.applicant" placeholder="请选择申请人" :max-show="1" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请单位" prop="applicantUnit">
                  <treeselect v-model="form.applicantUnit" :disabled="isView" :options="deptOptions" :show-count="true"
                              placeholder="请选择申请单位"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="被导出人" prop="exportedPerson">
                  <person-select v-model="form.exportedPerson" :disabled="isView" placeholder="请选择被导出人"
                                 :max-show="1"></person-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="导出格式" prop="exportFormat">
                  <el-radio v-for="item in exportedFormatOptions" :disabled="isView" v-model="form.exportFormat"
                            :label="item.value"
                            :key="item.value">{{ item.label }}
                  </el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="导出类型" prop="exportType">
                  <el-select v-model="form.exportType" :disabled="isView" placeholder="请选择导出类型"
                             style="width: 100%" @change="exportTypeChange">
                    <el-option
                        v-for="item in exportTypeOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="档案类型" prop="fileType">
              <el-switch
                  :disabled="docOptions.length===0"
                  v-model="selectAllDoc"
                  active-text="全选"
                  inactive-text="取消"
                  @change="selectAllDocChangeHandel"
              >
              </el-switch>
              <el-tree
                  ref="docTree"
                  empty-text="请现选择被导出人"
                  :data="docOptions"
                  default-expand-all
                  check-on-click-node
                  @check="checkHandel"
                  show-checkbox
                  node-key="id"
                  :props="defaultProps">
              </el-tree>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="申请时间" prop="applicantDate">
                  <el-date-picker clearable size="small" style="width: 100%;"
                                  :disabled="isView"
                                  v-model="form.applicantDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择申请时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="到期时间" prop="endDate">
                  <el-date-picker clearable size="small" style="width: 100%;"
                                  :disabled="isView"
                                  v-model="form.endDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择到期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <!--            <el-form-item label="状态">-->
            <!--              <el-input v-model="form.status" placeholder="请输入状态"/>-->
            <!--            </el-form-item>-->
            <!--        <el-form-item label="审批状态">-->
            <!--          <el-radio-group v-model="form.approvalStatus">-->
            <!--            <el-radio label="1">请选择字典生成</el-radio>-->
            <!--          </el-radio-group>-->
            <!--        </el-form-item>-->
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :disabled="isView" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
          <div class="dialog-footer" style="float:right" v-if="flag">
            <el-button :loading="buttonLoading" type="info" @click="submitForm('zancun')">暂 存</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="审批历史" v-if="processInstanceId">
          <history ref="historyRef" :processInstanceId="processInstanceId"></history>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <verify ref="verifyRef" @submitCallback="submitCallback" :taskId="taskId" :taskVariables="taskVariables"
            :sendMessage="sendMessage"></verify>
  </div>
</template>

<script>
import {addExportNet, delExportNet, exportExportNet, getExportNet, listExportNet, updateExportNet} from "@/api/business/exportNet";
import {getExportType, listExportType} from "@/api/business/exportType";
import UserSelect from "@/components/UserSelect/index.vue";
import PersonSelect from "@/components/PersonSelect/index.vue";
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import processApi from "@/api/workflow/processInst";
import history from "@/components/Process/History";
import verify from "@/components/Process/Verify";
import {mapGetters} from "vuex";
import {personFileTree} from "@/api/business/personFile";
import {getAllIds} from "@/utils/tree";

export default {
  name: "ExportNet",
  dicts: ['act_status'],
  components: {verify, history, PersonSelect, Treeselect, UserSelect},
  computed: {
    ...mapGetters(['userInfo']),
    docOptionsIds: function () {
      return getAllIds(this.docOptions, 'id');
    }
  },
  data() {
    return {
      // 流程实例
      processInstanceId: '',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //档案类型
      docOptions: [],
      selectAllDoc: 0,
      selectDocOptions: [],
      exportTypeOptions: [],
      exportedFormatOptions: [
        {
          value: '0',
          label: '文件夹导出'
        },
        {
          value: '2',
          label: '合并导出'
        }
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 总条数
      total: 0,
      // 内网导出表格数据
      exportNetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isView: false,
      // 部门树选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicant: null,
        applicantUnit: null,
        exportedPerson: null,
        fileType: null,
        applicantDate: null,
        status: null,
        approvalStatus: null,
        exportType: null,
        exportFormat: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        applicant: [
          {required: true, message: "申请人不能为空", trigger: "blur"}
        ],
        applicantUnit: [
          {required: true, message: "申请单位不能为空", trigger: "blur"}
        ],
        exportedPerson: [
          {required: true, message: "申请单位不能为空", trigger: "blur"}
        ],
        applicantDate: [
          {required: true, message: "申请时间不能为空", trigger: "blur"}
        ],
        endDate: [
          {required: true, message: "到期时间不能为空", trigger: "blur"}
        ],
      },
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {},
      processKey: 'exportNet'
    };
  },
  created() {
    this.getList();
  },
  watch: {
    'form.exportedPerson': function (newVal, oldVal) {
      if (newVal) {
        this.getDocOptions(newVal);
      } else {
        this.docOptions = []
      }
    }
  },
  methods: {
    checkHandel(node, data) {
      this.form.fileType = data.checkedKeys?.join(',');
    },
    /** 查询外网导出列表 */
    getList() {
      this.loading = true;
      this.getTreeselect();
      listExportNet(this.queryParams).then(response => {
        this.exportNetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applicant: this.userInfo.userId,
        applicantUnit: this.userInfo.dept.deptId,
        exportedPerson: null,
        fileType: null,
        applicantDate: null,
        endDate: null,
        status: null,
        approvalStatus: "0",
        remark: null,
        exportFormat: null,
        exportType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.docOptions = [];
      this.processInstanceId = undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.flag = true
      this.isView = false;
      this.reset();
      this.getTreeselect();
      this.getExportTypeOptions();
      this.selectDocOptions = [];
      this.open = true;
      this.title = "添加外网导出";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.flag = true
      this.isView = false;
      this.reset();
      this.getTreeselect();
      this.getExportTypeOptions();
      this.selectDocOptions = [];
      const id = row.id || this.ids
      getExportNet(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.$nextTick(() => {
          this.processInstanceId = response.data.actBusinessStatus.processInstanceId;
          let fileTypeIds = response.data.fileType.split(',');
          this.$refs.docTree.setCheckedKeys(fileTypeIds)
        })

        this.open = true;
        this.title = "修改外网导出";
        this.sendMessage = {
          title: '外网导出申请',
          messageContent: '单据【' + row.id + "】申请"
        }
      });
    },
    async handleDown(row) {
      this.loading = true;
      await this.$download.zip('/business/exportNet/getByFileId/' + row.id, row.exportedPersonName + row.applicantDate + '外网导出.zip');
      this.loading = false;
    },
    handleView(row) {
      this.flag = false
      this.isView = true;
      this.loading = true;
      this.getExportTypeOptions();
      this.selectDocOptions = [];
      this.reset();
      const id = row.id || this.ids
      getExportNet(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.$nextTick(() => {
          this.processInstanceId = response.data.actBusinessStatus.processInstanceId;
          let fileTypeIds = response.data.fileType.split(',');
          this.$refs.docTree.setCheckedKeys(fileTypeIds)
        })

        this.open = true;
        this.title = "查看外网导出";
      });
    },
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getDocOptions(personId) {
      personFileTree(personId).then(response => {
        this.docOptions = response.data;
      })
    },
    getExportTypeOptions() {
      listExportType().then(response => {
        this.exportTypeOptions = response.rows;
      })
    },
    selectAllDocChangeHandel(value) {
      if (value) {
        this.$refs.docTree.setCheckedKeys(this.docOptionsIds)
      } else {
        this.$refs.docTree.setCheckedKeys([]);
      }
    },
    exportTypeChange() {
      if (this.form.exportType) {
        this.selectDocOptions = [];
        getExportType(this.form.exportType).then(response => {
          let typeId = response.data.typeId.split(',');
          for (let i = 0; i < typeId.length; i++) {
            this.selectDocOptions.push(Number(typeId[i]));
          }
          this.$refs.docTree.setCheckedKeys(this.selectDocOptions);
        });
      }
    },
    /** 提交按钮 */
    submitForm(flag) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateExportNet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              if (flag === 'submit') {
                this.submitFormApply(response.data)
              }
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addExportNet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              if (flag === 'submit') {
                this.submitFormApply(response.data)
              }
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 提交成功回调
    submitCallback() {
      this.open = false;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除外网导出编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delExportNet(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有外网导出数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportExportNet(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    //提交流程
    submitFormApply(entity) {
      //流程变量
      this.taskVariables = {
        entity: entity,
        userId: '1',
        //assigneeList: assigneeList
      }
      const data = {
        processKey: this.processKey, // key
        businessKey: entity.id, // 业务id
        variables: this.taskVariables,
        classFullName: 'com.ruoyi.business.domain.FileInternetExport'
      }
      // 启动流程
      processApi.startProcessApply(data).then(response => {
        this.taskId = response.data.taskId;
        this.$refs.verifyRef.visible = true
        this.$refs.verifyRef.reset()
      })
    },
    //撤回
    cancelProcessApply(row) {
      this.$modal.confirm('是否撤销申请').then(() => {
        this.loading = true;
        return processApi.cancelProcessApply(row.actBusinessStatus.processInstanceId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).finally(() => {
        this.loading = false;
      });
    }
  }
};
</script>
